package com.down;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.SSLSocketFactory;

import com.alibaba.fastjson.JSONObject;

public class BioFileDownloader {
	//http://b.zol-img.com.cn/desk/bizhi/image/3/960x600/1373459291705.jpg
	
	
	static File file = new File("F:/downimg/123.png");
	public static void main1() throws Exception {
		//String urlStr = "https://img.alicdn.com/bao/uploaded/i3/TB12R13NXXXXXb6XVXXXXXXXXXX_!!0-item_pic.jpg";
		String urlStr = "https://www.baidu.com/img/bd_logo1.png";
		//String urlStr = "http://b.zol-img.com.cn/desk/bizhi/image/3/960x600/1373459291705.jpg";
		//String urlStr = "http://vip.qq.com/qq.html";
		URL url = new URL(urlStr);
		Socket socket = buildSocket(url);
		
		OutputStream out = socket.getOutputStream();
		BufferedOutputStream bufferedOut = new BufferedOutputStream(out);
		bufferedOut.write(("GET "+url.getPath()+" HTTP/1.1\r\n").getBytes());
		bufferedOut.write(("host:"+url.getHost()+ "\r\n").getBytes());
		/*bufferedOut.write(":authority:img.alicdn.com\r\n".getBytes());
		bufferedOut.write(":method:GET\r\n".getBytes());
		bufferedOut.write(":path:/bao/uploaded/i3/TB12R13NXXXXXb6XVXXXXXXXXXX_!!0-item_pic.jpg_430x430q90.jpg\r\n".getBytes());
		bufferedOut.write(":scheme:https\r\n".getBytes());
		bufferedOut.write("accept-encoding:gzip, deflate, sdch, br\r\n".getBytes());
		bufferedOut.write("accept-language:zh-CN,zh;q=0.8\r\n".getBytes());
		bufferedOut.write("cache-control:max-age=0\r\n".getBytes());
		bufferedOut.write("upgrade-insecure-requests:1\r\n".getBytes());
		bufferedOut.write("cache-control:no-cache\r\n".getBytes());
		bufferedOut.write("pragma:no-cache\r\n".getBytes());
		bufferedOut.write("user-agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36\r\n".getBytes());
		
		*/
		//bufferedOut.write("accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\r\n".getBytes());
		bufferedOut.write("\r\n\r\n".getBytes());
		bufferedOut.flush();
		InputStream inputStream = socket.getInputStream();
		int i = 0;
		List<StringBuilder> sbLineList = new ArrayList<StringBuilder>();
		JSONObject responseMap = new  JSONObject();
		
		StringBuilder sb = null;
		boolean isLength = false;
		while((i= inputStream.read())>-1){
			char c = (char)i;
			if(sb==null){
				sb=new StringBuilder();
			}
			sb.append(c);
			if(c=='\n'){
				
				if(sb!=null){
					sbLineList.add(sb);
					initResponseHeader(responseMap, sb);
					if(isLength){
						if(!responseMap.containsKey("Content-Length")){
							responseMap.put("Content-Length",Integer.valueOf(sb.substring(0,sb.length()-2), 16));
						}
						break;
					}
				}
				if(sb.length()==2){
					isLength=true;
					if(responseMap.containsKey("Content-Length")){
						break;
					}
				}
				System.out.println(sb);
				sb = null;
			}
		}
		if(responseMap.getInteger("code")==null||responseMap.getInteger("code")!=200){
			System.out.println(responseMap.getInteger("code"));
			return;
		}
		int bodyInt = -1;
		int length = responseMap.getInteger("Content-Length"); //102675
		System.out.println(responseMap);
		byte[] body = new byte[1024]; //1kb 
		while((bodyInt=inputStream.read(body))>-1){
			//String bodyStr = new String(body,"utf-8");
			//System.out.println(bodyStr);
			fileOutput.write(body,0,bodyInt);
			
			length = length-bodyInt;
			System.out.println("bodyInt:"+bodyInt);
			System.out.println("no read:"+length);
			System.out.println("--------------------------");
			if(length<=0){
				break;
			}
		}
		fileOutput.flush();
		fileOutput.close();
		inputStream.close();
		socket.close();
		
	}




	private static void initResponseHeader(JSONObject responseMap,
			StringBuilder sb) {
		int a = sb.indexOf("Content-Length: ");
		if(a>-1){
			responseMap.put("Content-Length", sb.substring("Content-Length: ".length(), sb.length()-2));
		}
		a = sb.indexOf("HTTP/1.1");
		if(a>-1){
			responseMap.put("code", sb.substring("HTTP/1.1".length()+1, "HTTP/1.1".length()+4));
		}
	}




	private static Socket buildSocket(URL url)
			throws Exception {
		//SocketAddress address = new InetSocketAddress("183.61.236.54",3128) ;
		//Proxy proxy = new Proxy(java.net.Proxy.Type.HTTP,address);
		//Socket socket = new Socket(proxy);
		//return new Socket("127.0.0.1",8787);
		//设置代理.	    
		String proxyHost = "127.0.0.1";
		int proxyPort =8787;
		// 设置认证
//		Authenticator.setDefault(new Authenticator() {
//			protected PasswordAuthentication getPasswordAuthentication() {
//				return new PasswordAuthentication("username", "password"
//						.toCharArray());
//			}
//		});//Proxy proxy = new Proxy(Proxy.Type.DIRECT, addr);  
		
		
		String host = url.getHost();
		String urlStr = url.toString();
		int port = url.getPort()<0&&urlStr.startsWith("http:")?80:443;
		SocketAddress addr = new InetSocketAddress(proxyHost, proxyPort);
		Socket socket = null;
		if(urlStr.startsWith("http:")){
			socket = new Socket(host, port); 
		}else{
			socket = SSLSocketFactory.getDefault().createSocket(host, port);
		}
		//InetSocketAddress dest = new InetSocketAddress(host, port);  
		/*
		 trustAllHttpsCertificates();  
		 HostnameVerifier hv = new HostnameVerifier() {  
				@Override
				public boolean verify(String hostname, SSLSession session) {
					// TODO Auto-generated method stub
					return true;
				}  
		    };  
		 HttpsURLConnection.setDefaultHostnameVerifier(hv);  */
		//socket.connect(dest,10000); 
		return socket;
	}
	
	
      
    private static void trustAllHttpsCertificates() throws Exception {  
        javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];  
        javax.net.ssl.TrustManager tm = new miTM();  
        trustAllCerts[0] = tm;  
        javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext  
                .getInstance("SSL");  
        sc.init(null, trustAllCerts, null);  
        javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc  
                .getSocketFactory());  
    }  
  
    static class miTM implements javax.net.ssl.TrustManager,  
            javax.net.ssl.X509TrustManager {  
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {  
            return null;  
        }  
  
        public boolean isServerTrusted(  
                java.security.cert.X509Certificate[] certs) {  
            return true;  
        }  
  
        public boolean isClientTrusted(  
                java.security.cert.X509Certificate[] certs) {  
            return true;  
        }  
  
        public void checkServerTrusted(  
                java.security.cert.X509Certificate[] certs, String authType)  
                throws java.security.cert.CertificateException {  
            return;  
        }  
  
        public void checkClientTrusted(  
                java.security.cert.X509Certificate[] certs, String authType)  
                throws java.security.cert.CertificateException {  
            return;  
        }  
    }  
	
public static void main(String[] args) throws Exception {
	main1();
}
static OutputStream fileOutput = null;
static {
	try {
		if (!file.exists()) {
			file.createNewFile();
		}
		fileOutput = new BufferedOutputStream(new FileOutputStream(file));
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

}
}
